<?php
namespace app\shop\controller;
use app\ApiRest;

use app\massage\model\Coupon;
use app\massage\model\CouponRecord;
use app\shop\model\Address;
use app\shop\model\Car;
use app\shop\model\Config;
use app\shop\model\Goods;
use app\shop\model\MsgConfig;
use app\shop\model\Order;
use app\shop\model\OrderAddress;
use app\shop\model\OrderGoods;
use app\shop\model\RefundOrder;
use app\shop\model\User;
use think\App;
use think\facade\Db;
use think\Request;


class IndexOrder extends ApiRest
{

    protected $model;

    protected $refund_model;

    protected $order_goods_model;

    public function __construct(App $app) {

        parent::__construct($app);

        $this->model = new Order();

        $this->refund_model = new RefundOrder();

        $this->order_goods_model = new OrderGoods();

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-19 15:48
     * @功能说明:个人中心
     */
    public function orderList(){
        //超时自动取消订单
        $this->model->autoCancelOrder($this->_uniacid,$this->getUserId());

        $input = $this->_param;

        $dis[] = ['a.uniacid','=',$this->_uniacid];

        $dis[] = ['a.user_id','=',$this->getUserId()];

        $where = [];

        if(!empty($input['name'])){

            $where[] = ['b.goods_name','like','%'.$input['name'].'%'];

            $where[] = ['a.order_code','like','%'.$input['name'].'%'];

        }

        if(!empty($input['pay_type'])){

            $dis[] = ['a.pay_type','=',$input['pay_type']];

        }

        $data = $this->model->indexDataList($dis,$where);

        if(!empty($data['data'])){

            foreach ($data['data'] as &$v){

                $can_refund_num = is_array($v['order_goods'])?array_sum(array_column($v['order_goods'],'can_refund_num')):0;

                if(!empty($v['add_price'])&&$v['add_price_refund']==0){

                    $can_refund_num+=1;
                }
                //是否可以申请退款
                if(($v['pay_type']==7&&$v['can_refund_time']>time()&&$can_refund_num>0)||($v['pay_type']==2&&$can_refund_num>0)){

                    $v['can_refund'] = 1;

                }else{

                    $v['can_refund'] = 0;
                }

            }

        }

        return $this->success($data);

    }

    /**
     * @author chenniang
     * @DataTime: 2021-03-15 14:58
     * @功能说明:订单详情
     */
    public function orderInfo(){

        $input = $this->_param;


        $dis = [

            'id' => $input['id']
        ];

        $data = $this->model->dataInfo($dis);

        $data['over_time'] -= time();

        $data['create_time'] = date('Y-m-d H:i:s',$data['create_time']);
        //剩余可申请退款数量
        $can_refund_num = array_sum(array_column($data['order_goods'],'can_refund_num'));
        //如果有跑腿业务 可退款数量+1
        if(!empty($data['add_price'])&&$data['add_price_refund']==0){

            $can_refund_num+=1;
        }
        //是否可以申请退款
        if(($data['pay_type']==7&&$data['can_refund_time']>time()&&$can_refund_num>0)||($data['pay_type']==2&&$can_refund_num>0)){

            $data['can_refund'] = 1;

        }else{

            $data['can_refund'] = 0;
        }

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-19 17:29
     * @功能说明:退款订单详情
     *
     */
    public function refundOrderList(){

        $input = $this->_param;

        $dis[] = ['a.uniacid','=',$this->_uniacid];

        $dis[] = ['a.user_id','=',$this->getUserId()];

        $where = [];

        if(!empty($input['name'])){

            $where[] = ['b.goods_name','like','%'.$input['name'].'%'];

            $where[] = ['a.order_code','like','%'.$input['name'].'%'];

        }

        if(!empty($input['status'])){

            $dis[] = ['a.status','=',$input['status']];

        }else{

            $dis[] = ['a.status','>',-1];

        }

        $data = $this->refund_model->indexDataList($dis,$where);

        return $this->success($data);


    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-19 17:50
     * @功能说明:退款订单详情
     */

    public function refundOrderInfo(){

        $input = $this->_param;

        $dis = [

            'id' => $input['id']
        ];

        $data = $this->refund_model->dataInfo($dis);

        $data['create_time'] = date('Y-m-d H:i:s',$data['create_time']);

        $data['refund_time'] = date('Y-m-d H:i:s',$data['refund_time']);

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-09-01 16:08
     * @功能说明:配送方式
     */
    public function goodsSendType(){

        $input = $this->_param;

        $car_model = new Car();

        $is_show = isset($input['is_show'])?$input['is_show']:1;

        $list = $car_model->carList($this->getUserId(),1,0,$is_show);

        $data['is_self'] = 0;

        $data['is_send'] = 0;

        if(!empty($list)){

            foreach ($list as &$value){

                $data['is_self'] = !empty($value['is_self'])?$value['is_self']:$data['is_self'];

                $data['is_send'] = !empty($value['is_send'])?$value['is_send']:$data['is_send'];

            }

        }

        return $this->success($data);

    }





    /**
     * @author chenniang
     * @DataTime: 2021-03-22 09:43
     * @功能说明:下单页面详情
     */
    public function payOrderInfo(){

        $input = $this->_param;

        $send_type  = !empty($input['send_type'])?$input['send_type']:0;

        $is_show    = isset($input['is_show'])?$input['is_show']:1;

        $no_i       = isset($input['no_i'])?$input['no_i']:1;

        $coupon_id  = isset($input['coupon_id'])?$input['coupon_id']:0;

        $order_info = $this->model->payOrderInfo($this->getUserId(),$is_show,$no_i,$send_type,$coupon_id);

        $address_model = new Address();

        if(!empty($input['address_id'])){
            //默认地址
            $order_info['address_info'] = $address_model->dataInfo(['id'=>$input['address_id']]);

        }
        //自提地址
        if($send_type==1){

            $config_model = new \app\massage\model\Config();

            $config = $config_model->dataInfo(['uniacid'=>$this->_uniacid]);

            $order_info['address_info'] = [

                'mobile' => $config['mobile'],

                'lat' => $config['zt_lat'],

                'lng' => $config['zt_lng'],

                'address' => $config['zt_address'],

                'address_id' => 0,

                'user_name' => $config['app_name'],

            ];

        }

        $coupon_modle  = new Coupon();

        $coupon_record_model  = new CouponRecord();
        //可用优惠券数量
        $canUseCoupon = $coupon_modle->canUseCoupon($this->getUserId(),2,$is_show,$no_i);

        $order_info['canUseCoupon'] = $coupon_record_model->where('id','in',$canUseCoupon)->sum('num');

        return $this->success($order_info);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-22 09:53
     * @功能说明:下单
     */
    public function payOrder(){

        $input = $this->_input;

        $send_type  = isset($input['send_type'])?$input['send_type']:1;

        $is_show    = isset($input['is_show'])?$input['is_show']:1;

        $no_i       = isset($input['no_i'])?$input['no_i']:1;

        $coupon_id  = !empty($input['coupon_id'])?$input['coupon_id']:0;

        $order_info = $this->model->payOrderInfo($this->getUserId(),$is_show,$no_i,$send_type,$coupon_id);

        $config_model = new Config();

        $address_order_model = new OrderAddress();

        $config = $config_model->dataInfo(['uniacid'=>$this->_uniacid]);

        $member_config_model = new \app\member\model\Config();

        $member_config = $member_config_model->configInfo(['uniacid'=>$this->_uniacid]);

        Db::startTrans();

        $order_insert = [

            'uniacid'    => $this->_uniacid,

            'order_code' => orderCode(),

            'user_id'    => $this->getUserId(),

            'pay_price'  => $order_info['pay_price'],

            'true_price' => $order_info['pay_price'],

            'pay_type'   => 1,

            'goods_price'=> $order_info['goods_price'],

            'true_goods_price'=> $order_info['goods_price'],

            'init_price'   => $order_info['init_price'],

            'init_goods_price' => $order_info['init_goods_price'],

            'text'         => $input['text'],

            'over_time'    => time()+$config['over_time']*60,

            'send_type'    => $send_type,

            'integral'     => $order_info['integral'],

            'discount'     => $order_info['discount'],

            'freight'      => $order_info['freight'],
            //会员折扣抵扣了多少钱
            'member_discount_price'   => $order_info['member_discount_price'],

            'integral_discount_price' => $order_info['integral_discount_price'],

            'balance'      => !empty($input['is_balance'])?$order_info['pay_price']:0,
            //付费获得的积分
            'get_integral' => empty($input['is_balance'])?floor($order_info['pay_price']*$member_config['integral_cash']):0,

        ];

        //下单
        $res = $this->model->dataAdd($order_insert);

        if($res!=1){

            Db::rollback();

            $this->errorMsg('下单失败');
        }

        $order_id = $this->model->getLastInsID();

        if($send_type==2){
            //添加下单地址
            $res = $address_order_model->orderAddressAdd($input['address_id'],$order_id);

        }else{

            $res = $address_order_model->selfAddressAdd($this->_uniacid,$order_id,$input['user_name'],$input['mobile']);

        }

        if(!empty($res['code'])){

            Db::rollback();

            $this->errorMsg($res['msg']);

        }

        $order_insert['id'] = $order_id;

        //使用优惠券
        if(!empty($order_info['coupon_id'])){

            $coupon_record_model = new CouponRecord();

            $coupon_id = $coupon_record_model->couponUse($order_info['coupon_id'],$order_id);

            $this->model->dataUpdate(['id'=>$order_id],['coupon_id'=>$coupon_id]);

        }

        if(empty($order_info['order_goods'])){

            $this->errorMsg('订单错误');
        }
        //添加到子订单
        $res = $this->order_goods_model->orderGoodsAdd($order_info['order_goods'],$order_id,$is_show,$this->getUserId());

        if(!empty($res['code'])){

            Db::rollback();

            $this->errorMsg($res['msg']);
        }
        //积分活动
        $res = $this->model->marketingCheck($order_insert,$order_info['order_goods']);

        if(!empty($res['code'])){

            Db::rollback();

            $this->errorMsg($res['msg']);

        }

        Db::commit();
        //如果是0元
        if($order_insert['pay_price']<=0){

            $this->model->orderResult($order_insert['order_code'],$order_insert['order_code']);

            return $this->success(true);
        }
        //余额支付
        if(!empty($input['is_balance'])){

            $user_model = new \app\massage\model\User();

            $user_balance= $user_model->where(['id'=>$this->getUserId()])->value('balance');

            if($user_balance<$order_insert['pay_price']){

                $this->errorMsg('余额不足');
            }

            $this->model->orderResult($order_insert['order_code'],$order_insert['order_code']);

            return $this->success(true);

        }
        //微信支付
        $pay_controller = new IndexWxPay($this->app);
        //支付
        $jsApiParameters= $pay_controller->createWeixinPay($this->payConfig(),$this->getUserInfo()['openid'],$this->_uniacid,"团购",['type' => 'SchoolShop' , 'out_trade_no' => $order_insert['order_code']],$order_insert['pay_price']);

        $arr['pay_list']= $jsApiParameters;

        return $this->success($arr);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-25 15:59
     * @功能说明:重新支付
     */
    public function rePayOrder(){

        $input = $this->_input;

        $order_insert = $this->model->dataInfo(['id'=>$input['id']]);

        if($order_insert['pay_type']!=1){

            $this->errorMsg('订单状态错误');

        }
        //余额支付
        if(!empty($order_insert['balance'])){

            $user_model = new \app\massage\model\User();

            $user_balance= $user_model->where(['id'=>$this->getUserId()])->value('balance');

            if($user_balance<$order_insert['pay_price']){

                $this->errorMsg('余额不足');
            }

            $this->model->orderResult($order_insert['order_code'],$order_insert['order_code']);

            return $this->success(true);

        }
        //微信支付
        $pay_controller = new IndexWxPay($this->app);
        //支付
        $jsApiParameters= $pay_controller->createWeixinPay($this->payConfig(),$this->getUserInfo()['openid'],$this->_uniacid,"团购",['type' => 'SchoolShop' , 'out_trade_no' => $order_insert['order_code']],$order_insert['pay_price']);

        $arr['pay_list']= $jsApiParameters;

        return $this->success($arr);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-25 16:38
     * @功能说明:取消订单
     */

    public function cancelOrder(){

        $input = $this->_input;

        $order_insert = $this->model->dataInfo(['id'=>$input['id']]);

        if($order_insert['pay_type']!=1){

            $this->errorMsg('订单状态错误');

        }

       $res = $this->model->cancelOrder($order_insert);

       if(!empty($res['code'])){

           $this->errorMsg($res['msg']);
       }

       return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-26 11:39
     * @功能说明:申请退款
     */
    public function applyOrder(){

        $input = $this->_input;

        $order = $this->model->dataInfo(['id'=>$input['order_id']]);

        if(empty($order)){

            $this->errorMsg('订单未找到');
        }

        if($order['pay_type']<2&&$order['have_tx']!=0){

            $this->errorMsg('订单状态错误');

        }

        if(empty($input['list'])){

            $this->errorMsg('请选择商品');

        }

        if($order['can_refund_time']<time()&&$order['pay_type']==7){

            $this->errorMsg('核销后24小时内才能申请退款哦');

        }
        //申请退款
        $res = $this->refund_model->applyRefund($order,$input);

        if(!empty($res['code'])){

            $this->errorMsg($res['msg']);
        }
//        //给楼长发送服务通知
//        $msg_model = new MsgConfig();
//
//        $refund_order = $this->refund_model->dataInfo(['id'=>$res]);
//        //发送通知
//        $msg_model->refundSendMsg($refund_order);

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-26 15:55
     * @功能说明:取消退款
     */
    public function cancelRefundOrder(){

        $input = $this->_input;

        $order = $this->refund_model->dataInfo(['id'=>$input['id']]);

        if($order['status']!=1){

            $this->errorMsg('订单已经审核');

        }

        Db::startTrans();

        $res = $this->refund_model->dataUpdate(['id'=>$input['id']],['status'=>-1,'cancel_time'=>time()]);

        if($res!=1){

            Db::rollback();

            $this->errorMsg('取消失败');
        }

        if(!empty($order['order_goods'])){

            $order_goods_model = new OrderGoods();

            foreach ($order['order_goods'] as $v){

                if(!empty($v['order_goods_id'])){

                    $num = $v['goods_num'];

                    $res = $order_goods_model->where(['id'=>$v['order_goods_id']])->update(['can_refund_num'=>Db::Raw("can_refund_num+$num")]);

                    if($res!=1){

                        Db::rollback();

                        $this->errorMsg('取消失败');
                    }

                }else{

                    $this->model->dataUpdate(['id'=>$order['order_id']],['add_price_refund'=>0]);

                }

            }

        }

        Db::commit();

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-04-07 15:30
     * @功能说明:刷新订单二维码
     */
    public function refreshQr(){

        $input = $this->_input;

        $qr_insert = [

            'id' => $input['id']
        ];
        //获取二维码
        $qr = $this->model->orderQr($qr_insert,$this->_uniacid);

        if(!empty($qr)){

            $this->model->dataUpdate(['id'=>$input['id']],['qr'=>$qr]);

        }

        return $this->success($qr);
    }



    /**
     * @author chenniang
     * @DataTime: 2021-03-25 17:14
     * @功能说明:楼长核销订单
     */
    public function endOrder(){

        $input = $this->_input;

        $order_model= new Order();

        $order = $order_model->dataInfo(['id'=>$input['id']]);

        if(empty($order)){

            $this->errorMsg('订单未找到');
        }

        if(empty($order)){

            $this->errorMsg('订单未找到');
        }
        //自提
        if($order['send_type']==1&&$order['pay_type']!=2){

            $this->errorMsg('订单状态错误');
        }
        //快递
        if($order['send_type']==2&&$order['pay_type']!=3){

            $this->errorMsg('订单状态错误');
        }

        if($order['send_type']==1){

            $user_model = new \app\massage\model\User();

            $role =  $user_model->where(['id'=>$this->getUserId()])->value('role');

            if($role!=1){

                $this->errorMsg('只有管理员才能核销');
            }
        }

        $refund_model = new RefundOrder();
        //判断有无申请中的退款订单
        $refund_order = $refund_model->dataInfo(['order_id'=>$order['id'],'status'=>1]);

        if(!empty($refund_order)){

            $this->errorMsg('该订单正在申请退款，请先处理再核销');

        }

        $res = $order_model->hxOrder($input['id'],$this->getUserId());

        return $this->success($res);


    }

    public function getPayNumber(){

        $input = $this->_input;

        $number= $this->order_goods_model->getGoodsNumber(['a.goods_id'=>$input['id'],'b.user_id'=>$this->getUserId()] );

        return $this->success(['number'=>$number]);
    }


    /**
     * @author chenniang
     * @DataTime: 2021-07-10 00:40
     * @功能说明:可用的优惠券列表
     */
    public function couponList(){

        $input = $this->_param;

        $coupon_model = new Coupon();

        $coupon_record_model = new CouponRecord();

        $is_show = isset($input['is_show'])?$input['is_show']:1;

        $coupon_id = $coupon_model->canUseCoupon($this->getUserId(),2,$is_show);

        $data = $coupon_record_model->where('id','in',$coupon_id)->order('id desc')->paginate(10)->toArray();

        if(!empty($data['data'])){

            foreach ($data['data'] as &$v){

                $v['start_time'] = date('Y.m.d H:i',$v['start_time']).' - '.date('Y.m.d H:i',$v['end_time']);

            }
        }

        return $this->success($data);

    }

}
